<template>
  <div class="form-attachment">
    <!-- S 智能质检 -->
    <div v-if="intelligentCheckNow" class="intelligent-container">
      <div class="intelligent-tips" :class="abnormalStyle">
        
        <div v-if="showIntellTip && intelligentFieldsLength && intelligentFields.inputCount > 0">
          <i class="iconfont" :class="iconStyle"></i>  
          <i18n path="common.form.tip.attachment.tips1">
            <span place="data1">{{ showIntellInput }}</span>
            <span place="data2">{{ intelligentFields.minPictureCheckScore }}</span>
            <span place="data3">{{ intelligentFields.passCount }}</span>
          </i18n>
          <template v-if="minTaskCheckScore">
            <i18n path="common.form.tip.attachment.tips2">
              <span place="data1">{{ intelligentFields.pass ? $t('common.base.exceed') : $t('common.base.lowerThan') }}</span>
              <span place="data2">{{ intelligentFields.minTaskCheckScore }}</span>
            </i18n>
          </template>
          <template v-if="minTaskCheckScore && minTaskCheckCount">
            {{$t('common.base.or')}}
          </template>
          <template v-if="minTaskCheckCount">
            <i18n path="common.form.tip.attachment.tips3">
              <span place="data1">{{ intelligentFields.pass ? $t('common.base.exceed') : $t('common.base.lowerThan') }}</span>
              <span place="data2">{{ intelligentFields.minTaskCheckCount }}</span>
            </i18n>
          </template>
          <i18n path="common.form.tip.attachment.tips4">
            <span place="data1">{{ intelligentFields.pass ? $t('common.base.qualified') : $t('common.base.abnormal') }}</span>
          </i18n>
        </div>
        <div v-else><i class="iconfont icon-info colorFAAD14"></i>{{$t('common.form.tip.attachment.tips5')}}</div>
        
        <el-button @click="openIntelligentStandard()" type="text">{{$t('common.form.preview.attachment.qualityInspectionSpecification')}}</el-button>
      </div>
    </div>
    <!-- E 智能质检 -->
    <base-upload 
      @input="input" 
      :is-water-mark="isWaterMark" 
      :accept='field.accept' 
      :value="_value" 
      :action="field.action" 
      :field="field"
      :action-options="field.actionOptions" 
      :action-storage="field.actionStorage" 
      :limit="(field.setting && field.setting.fileLimit) ? field.setting.fileLimit : (field.limit || defautUploadMax)" 
      :for-id="`form_${field.fieldName}`" 
      :placeholder="placeHolder" 
      :intelligent-check-now="intelligentCheckNow" 
      :formEditingMode="formEditingMode" 
      @getDeleteFiles="(value)=>{$emit('getDeleteFiles',(value))}">
    </base-upload>
    <div v-if="field.tips" class="font-12 color-999 atta-tips">{{field.tips}}</div>

    <!-- 质检规范 -->
    <intelligent-standard-dialog 
      ref="intelligentStandard"
      :intelligent-config="intelligentConfig"
    />
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';

import Uploader from '@src/util/uploader';
import platform from '@src/platform'

import * as SettingTaskApi from '@src/api/SettingTaskApi.js';
import _ from 'lodash'
import IntelligentStandardDialog from './components/IntelligentStandardDialog.vue';
import i18n from '@src/locales';


export default {
  name: 'form-attachment',
  mixins: [FormMixin],
  inject: {
    initData: {
      default: {}
    }
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    field: {
      type: Object,
      default: () => ({})
    },
    intelligentConfigNew: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: ''
    },
    // 表单操作模式
    formEditingMode: {
      type: String,
      default: '', // create | edit
    },
  },
  data() {
    return {
      isWaterMark: false,
      defautUploadMax:Uploader.FILE_MAX_NUM,

      // 智能质检
      intelligentFields: {}
    }
  },
  watch: {
    field(val) {
      // 切换工单类型清空质检字段 先这么判断
      this.intelligentFields = {}
    }
  },
  computed: {
    _value(){
      // value 是通过后端数据给的，但是会存在有的数据为 [null, null] 的情况，且后端定位不到问题，所以前端进行过滤。
      return this.value?.length ? this.value.filter(item => item && item.id) : []
    },
    placeHolder() {
      return `${!this.field.isNull ? i18n.t('common.base.isArrRequire') : ''}${this.field.placeHolder || ''}`;
    },
    // 智能质检显示逻辑
    intelligentShow() {
      return this.intelligentConfigNew && Object.keys(this.intelligentConfigNew).length > 0
    },
    // 实时智能质检字段显示逻辑
    intelligentCheckNow() {
      if (this.intelligentConfigNew && Object.keys(this.intelligentConfigNew).length > 0) {
        if (Reflect.has(this.intelligentConfigNew, 'pictureCheckSwitch') && this.intelligentConfigNew.pictureCheckSwitch && this.intelligentConfigNew.nowCheck) {
          if (Array.isArray(this.intelligentConfigNew.taskCheckFields) && this.intelligentConfigNew.taskCheckFields.length > 0) {
            // 如果这是工单回执
            if (this.mode === 'task_receipt') {
              return this.intelligentConfigNew.taskCheckFields.some(item => item.task_receipt === this.field.id)
            } else if (this.mode=== 'task') {
              return this.intelligentConfigNew.taskCheckFields.some(item => item.task === this.field.id)
            }
          }
          return false
        }
        return false
      }
      return false
    },
    // 智能质检字段
    intelligentConfig() {
      try {
        if (this.intelligentCheckNow) {
          return this.intelligentConfigNew || {}
        }
      } catch (error) {
        console.error(error)
      }
    },
    minTaskCheckScore() {
      return Reflect.has(this.intelligentFields, 'minTaskCheckScore') && _.isNumber(this.intelligentFields.minTaskCheckScore)
    },
    minTaskCheckCount() {
      return Reflect.has(this.intelligentFields, 'minTaskCheckCount') && _.isNumber(this.intelligentFields.minTaskCheckCount)
    },
    showIntellTip() {
      const isOneFile =  this.value.some(item => {
        return /\.(jpeg|jpg|png|bmp)$/i.test(item.filename)
      })
      // 如果没有一张图片符合 则不展示
      if (!isOneFile) return false
      return true
    },
    // 显示有效图片
    showIntellInput() {
      return this.value.filter(item => item.checked && /\.(jpeg|jpg|png|bmp)$/i.test(item.filename)).length;
    },
    intelligentFieldsLength() {
      const keys = Object.keys(this?.intelligentFields || {})
      return keys.length
    },
    abnormalStyle() {
      return this.intelligentFields?.pass ? ['qualified'] : ['abnormal']
    },
    iconStyle() {
      return this.intelligentFields?.pass ? ['icon-duihao', 'color52C41A'] : ['icon-info', 'colorFAAD14']
    }
  },
  methods: {
    input(newValue) {
      if (this.intelligentShow && !this.intelligentCheckNow) {
        newValue = newValue.map(item => {
          return {
            ...item,
            fieldId: this.field.id
          }
        })
      }
      if (this.intelligentCheckNow) {
        return this.aiCheckQualityBatch(newValue)
      }

      let oldValue = null;
      this.$emit('update', {newValue, oldValue, field: this.field});
      this.$emit('input', newValue);
    },
    aiCheckQualityBatch(newValue) {
      newValue = newValue.map(item => {
        return {
          ...item,
          type: 'TASK_TYPE',
          typeId: this.field.templateId,
          fieldId: this.field.id, // 字段id
          checked: item.checked ?? false,
          sim: item.sim ?? null,
          ossUrl: item.url ?? null,
          taskId: this?.initData?.task?.id || ''
        }
      })
      SettingTaskApi.aiCheckQualityBatch(newValue).then(res => {
        if(!res.success) {
          platform.notification({
            type: 'error',
            title: i18n.t('common.base.toast'),
            message: res.message
          })
          return
        }
        const result = res.result || {}
        const newValue = result.searchData
        this.intelligentFields = result

        let oldValue = null;
        this.$emit('update', {newValue, oldValue, field: this.field});
        this.$emit('input', newValue);
      }).catch(error => {
        console.warn(error);
      })
    },
    // 打开质检规范弹窗
    openIntelligentStandard() {
      this.$refs.intelligentStandard.open()
    },
  },
  mounted() {
    let { setting } = this.field;
    setting = setting || {};
    // 图片是否添加水印
    this.isWaterMark = (setting && !!setting.isAddWatermark);
  },
  components: {
    [IntelligentStandardDialog.name]: IntelligentStandardDialog
  }
}
</script>

<style lang="scss">
.form-attachment{
  width: 100%;

  .base-upload-btn{
    padding: 7px 12px;
    font-size: $font-size-small;
    border-radius: $button-radius-base;
    border-color: $color-primary;
  }
}
.atta-tips{
  margin-top: 5px;
}

// 智能质检
.intelligent-container {
  .intelligent-tips {
    padding: 8px;
    margin-bottom: 12px;
    border-radius: 4px;
    color: #595959;
    i {
      margin-right: 4px;
    }
  }
  .qualified {
    border: 1px solid #B7EB8F;
    background-color: #F6FFED;
  }
  .abnormal {
    border: 1px solid #FFE58F;
    background-color: #FFFBE6;
  }
  .color52C41A {
    color: #52C41A;
  }
  .colorFAAD14 {
    color: #FAAD14;
  }
}

</style>
